package com.cslc.mp.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

public class ValidateCodeServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static Logger logger = Logger.getLogger(ValidateCodeServlet.class.getName());
	/**
	 * Constructor of the object.
	 */
	public ValidateCodeServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//设置输出类型和浏览器不保存缓存  
        response.setContentType("image/jpeg") ;  
        response.setHeader("Cache-Control", "no-cache") ;  
          
        //创建图片对象  
        int width = 60,height = 30 ;  
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB) ;  
          
        Graphics g = image.getGraphics() ;  
        //填充背景色
        g.setColor(new Color(255, 255, 255));
        g.fillRect(1, 1, width - 1, height - 1);
        
        //设置边框颜色
        g.setColor(new Color(0, 0, 0));
        g.drawRect(0, 0, width-1, height-1);
        //生成随机数  
        Random random = new Random() ;  
        String s = "" ;  
        for(int i=0;i<4;i++){  
            s += random.nextInt(10) ;  
        }  
          
        //把随机数存到Session里面，便于等下比较  
        HttpSession session = request.getSession() ;  
        session.setAttribute("code",s) ;
              
        //随机生成颜色  Color color =  new Color(255,255,255) ;     random.nextInt(256)的值范围是0~255  
        Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)) ;  
          
        //把随机数写到图片上  
        String a = null ;  
        Font font = new Font(a,Font.ITALIC,18) ;  
        g.setColor(color) ;  
        g.setFont(font);  
        g.drawString(s,10,height-5) ;  
        g.dispose() ;    //关闭画笔  
          
        //把图片送到客户端  
        ServletOutputStream output = response.getOutputStream() ;  
        ImageIO.write(image,"JPEG",output) ;  
        output.flush();   //关闭输出流  
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String inputCode = request.getParameter("code");
		HttpSession session = request.getSession();
		String realCode = (String) session.getAttribute("code");
	
		logger.debug("输入的验证码：" + inputCode + "\n" + "实际验证码： " + realCode);
		JSONObject jsonObject = new JSONObject();
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		
		if(inputCode.equals(realCode)) {
			try {
				jsonObject.put("valid", true);
			}
			catch(JSONException e) {
				logger.error(e.getMessage());
			}
		}
		else {
			try {
				jsonObject.put("valid", false);
			} catch (JSONException e) {
				logger.error(e.getMessage());
			}
		}
		out.print(jsonObject);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
